﻿
import * as sqlite3 from "sqlite3";


class Row {
    adcode: number;
    center: string;
    citycode: number;
    level: string;
    name: string;
    polyline: string;
    parentId: number;
}

class DataAction {

    private db: sqlite3.Database;
    //private model: Model;
    constructor() {


        //sqliteDB: SqliteDB  sqliteDB = new SqliteDB("china_gis.db");
    }

    async init() {
        //this.db = connect("china_gis.db");
        //this.model = await this.db.model('games', {
        //    adcode: { type: Number },
        //    center: { type: String },
        //    citycode: { type: Number },
        //    level: { type: String },
        //    name: { type: String },
        //    polyline: { type: String },
        //    parentId: { type: Number },
        //    areaId: 'increments'          // special type, primary key
        //});


        this.db = new sqlite3.Database("china_gis.db", (err) => {
            if (err) {
                console.log('Could not connect to database', err)
            } else {
                console.log('Connected to database')
            }
        });

    }


    async updatePolyline(parentId: number, polyline: string): Promise<Boolean> {
        let strSql = `update china_area set  polyline=?   where areaId=?`;
        const updated = await new Promise<Boolean>((res, rej) => {
            var stmt = this.db.prepare(strSql, (err, row: any[]) => {
                if (err) rej(err);
                else res(true);
            });
            stmt.run([polyline, parentId]);
            stmt.finalize();
        })
        console.log(`完成Polyline更新:${parentId},${updated}`);
        return updated;

    }


    async insert(row: Row): Promise<number> {
        if (this.db != null) {
            return await new Promise<number>((resolve, reject) => {

                this.db.serialize(() => {
                    var db = this.db;
                    const colums: string[] = [];
                    const values: any[] = [];
                    for (var field in row) {
                        colums.push(field);
                        values.push(row[field]);
                    }
                    let strSql = `insert into china_area(${colums.join(',')}) values (?,?,?,?,?,?,?)`;
                    db.run(strSql, (err, row: any[]) => {
                        if (err) {
                            console.error(err);
                            rej(err);
                        }
                        else res(true);
                    })

                 

                    const inserted = await new Promise<Boolean>((res, rej) => {
                        var stmt = this.db.prepare(strSql, (err, row: any[]) => {
                            if (err) {
                                console.error(err);
                                rej(err);
                            }
                            else res(true);
                        });
                        stmt.run(values);
                        stmt.finalize();
                    })
                    console.log(`完成写入数据:${inserted},${JSON.stringify(row)}`);
                    if (inserted === true) {
                        var insertId = await new Promise<number>((res, rej) => {
                            this.db.get("select last_insert_rowid() as areaId", (err, dr: any) => {
                                console.log(`查询到写入结果:${err != null},${JSON.stringify(dr)}`);
                                if (err) {
                                    console.error(err);
                                    rej(err);
                                }
                                else {
                                    const areaId = dr["areaId"];
                                    res(areaId);
                                }
                            });
                        });
                        resolve(insertId);
                    } else {
                        reject(`写入数据错误:${JSON.stringify(row)}`);
                    }
                });


            });



        }
        //var result = await this.model.create(row);
        return 0;
    }

}

export {
    DataAction,
    Row
}